import SoundManager from "./SoundManager";
import GameData from "./GameData";
import GameDataInstance from "./GameDataInstance";

/** 全局工具类 */
export default class vv {
    /**扑克的方法集合 */
  

    /** 用户数据 */
    static user = {
        uid: null,
        uname: null,
        info: null
    };

    /** 房间数据 */
    static room = null;

    /**音频 */
    static audio = {
        volumeMusic: 0.8,//音量-音乐
        volumeSound: 0.8,//音量-音效
        musicId: null//背景音乐
    };

    /** 上一次显示提示的时间 */
    static showTipTime: Date = new Date();
    /**动态调整帧率的数量 */
    static dynamicFrameRateing: number = 0;

    /** 预制体是否正在打开中 */
    static prefabOpening: boolean = false;

    /** 屏幕适配 */
    static screenAdapter() {
        let canvas = cc.find("Canvas").getComponent(cc.Canvas);
        let winSize = cc.view.getVisibleSize();

        if (winSize.height / winSize.width <= 720 / 1280) {
            canvas.fitHeight = true;
            canvas.fitWidth = false;
        }
        else {
            canvas.fitHeight = false;
            canvas.fitWidth = true;
        }
    }

    /**动态调整游戏帧率 */
    static dynamicFrameRate(time) {
        this.dynamicFrameRateing++;
        cc.game.setFrameRate(40);
        setTimeout(() => {
            this.dynamicFrameRateing--;
            if (this.dynamicFrameRateing == 0) cc.game.setFrameRate(10);
        }, 1000 * time);
    }

    /** 禁止交互操作 */
    static pauseTouch(time?: number) {
        let MASK = cc.find("MASK");
        MASK.scale = 1;
        MASK.getComponent(cc.Sprite).scheduleOnce(() => {//等待超时
            MASK.scale = 0;
        }, time || 1);
    }

    /** 恢复交互操作 */
    static resumeTouch() {
        let MASK = cc.find("MASK");
        MASK.getComponent(cc.Sprite).unscheduleAllCallbacks();
        MASK.scale = 0;
    }

    /** 跳转场景 */
    static loadScene(sceneName: string, cb?: Function) {
        let MASK = cc.find("MASK");
        MASK.getComponent(cc.Sprite).unscheduleAllCallbacks();
        MASK.scale = 1;
        this.dynamicFrameRate(0.6);//动态调整游戏帧率
        MASK.runAction(cc.sequence(
            cc.fadeIn(0.3),
            cc.callFunc(() => {
                cc.director.loadScene(sceneName, () => {
                    if (cb) cb();
                });
            })
        ));
    }

    /** 事件监听 */
    static eventOn(event: string, cb: Function, target: object) {
        cc.find("Canvas").on(event, function (event) {
            cb(event.detail);
        }, target);
    }

    /** 事件监听(一次) */
    static eventOnce(event: string, cb: Function, target: object) {
        cc.find("Canvas").once(event, function (event) {
            cb(event.detail);
        }, target);
    }

    /** 事件发射 */
    static eventEmit(event: string, data?: any) {
        cc.find("Canvas").emit(event, data);
    }

    /** 播放音频 */
    static playAudio(url: string, loop?: boolean) {
        if (loop) {//音乐
            if (this.audio.musicId !== "null") cc.audioEngine.stop(this.audio.musicId);
            this.audio.musicId = cc.audioEngine.play(cc.url.raw('resources/Audio/' + url + '.wav'), true, this.audio.volumeMusic);

        }
        else {//音效
            cc.audioEngine.play(cc.url.raw('resources/Audio/' + url + '.wav'), false, this.audio.volumeSound);
        }
    }

    /** 提示框 font:显示的文字 */
    static showTip(font: string) {
        let time: Date = new Date();
        if (time.getTime() - this.showTipTime.getTime() < 800) return;
        this.showTipTime = time;

        cc.loader.loadRes("Prefab/tip", (err, prefab) => {
            if (err) {
                cc.log("加载预制体出错: " + err);
                return;
            }
            let node = cc.instantiate(prefab);
            node.x = cc.winSize.width / 2;
            node.y = cc.winSize.height / 2;
            node.getChildByName('tip').getComponent(cc.Label).string = font;
            node.parent = cc.director.getScene();

          //  this.dynamicFrameRate(3);//动态调整游戏帧率
            node.runAction(cc.sequence(
                cc.moveBy(0.3, 0, 60).easing(cc.easeOut(0.5)),
                cc.delayTime(3),
                cc.fadeOut(0.6),
                cc.callFunc(() => {
                    node.destroy();
                })
            ));
        });
    }

    /** 提示栏 font:显示的文字 */
    static showTipPanel(font: string, btnOKWord?: string, btnCancel?: string, cbBtnOK?: Function) {
        cc.loader.loadRes("Prefab/tipPanel", (err, prefab) => {
            if (err) {
                cc.log("加载预制体出错: " + err);
                return;
            }
            let node = cc.instantiate(prefab);
            node.getChildByName('tip').getComponent(cc.Label).string = font;
            node.parent = cc.find("Canvas");

            if (btnOKWord) {
                node.getChildByName('btnOK').getChildByName('lab').getComponent(cc.Label).string = btnOKWord;
            }

            if (btnCancel) {
                node.getChildByName('btnCancel').getChildByName('lab').getComponent(cc.Label).string = btnCancel;
                this.btnClick(node.getChildByName('btnCancel'), () => { node.destroy() });
                node.getChildByName('btnCancel').active = true;
            }
            else {
                node.getChildByName('btnOK').x = 0;
            }

            if (cbBtnOK) {
                this.btnClick(node.getChildByName('btnOK'), () => {
                    cbBtnOK(node);
                })
            }
            else {
                this.btnClick(node.getChildByName('btnOK'), () => {
                    node.destroy();
                })
                this.btnClick(node.getChildByName('M'), () => {
                    node.destroy();
                })
            }
        });
    }

    /** 添加按钮点击处理 */
    static btnClick(node: cc.Node, cb?: Function, noScale?: boolean, noPlayAudio?: boolean) {
        node.on('touchend', (event) => {
            if (!noPlayAudio) SoundManager.Instance.PlayEffect("down");
            if (cb) cb()
        });

        if (!noScale) {
            node.on('touchstart', (event) => {
                node.scale = 1.05;
            });
            node.on('touchend', (event) => {
                node.scale = 1;
            });
            node.on('touchcancel', (event) => {
                node.scale = 1;
            });
        }
    }


     //设置网络头像
     static SetWeChatImageByWebUrl(url:string,node:cc.Node)
     {
         cc.loader.load({url,type:'png'}, function (err, texture) 
         {
           var frame = new cc.SpriteFrame(texture);
           var w = node.width;
           var h = node.height;
           node.getComponent(cc.Sprite).spriteFrame = frame;
           node.width = w;
           node.height = h;
         });
     }

     /**通过url设置本地图片 */
     /**SetImageByLocalUrl("Sprite/D2_fuyang",sprite3); */
     static SetImageByLocalUrl(url:string,node:cc.Node)
     {
        cc.loader.loadRes(url,  cc.SpriteFrame,(err, frame) =>{
            if(err)
            {
                return;
            } 
             var w = node.width;
             var h = node.height;
             node.getComponent(cc.Sprite).spriteFrame = frame;
             node.width = w;
             node.height = h;
        })
     }


 /**根据模板实例化子物体 并重排 */
 static instantiateItem(parent:cc.Node,count:number,callback?:Function,item?:cc.Node)
 {
     parent.height = (count)*150+30
     var childCount = parent.childrenCount;
     if(!item)
     {
       if(parent.childrenCount>0) 
       { 
           item = parent.children[0];
       }
       else
       {
           return;
       }
     }
     for(let i=0;i<count;i++)
     {
         if(i>childCount-1)
         {
             var newItem = cc.instantiate(item);
             newItem.parent = parent;
         }
     }
     childCount = parent.childrenCount;
     for(let i=0;i<childCount;i++)
     {
         if(i<=count-1)
         {
             parent.children[i].active = true;
         }
         else
         {
              parent.children[i].active = false;
         }
     }

     if(parent.getComponent("cc.Layout"))
     {
         parent.getComponent("cc.Layout").updateLayout();
     }
     
     if(callback)callback();
 }

 //微信分享

 static share()
 {
    tt.onShareAppMessage(function () {
        return {
          title: '最新水果消消乐游戏，玩一整天都不会腻! ',
          imageUrl: 'http://sjh5.88youxi.cn/attachment/images/55/2018/09/eJV36ZRJjZjSBTls5Tj3kLR6fFL6st.png'
        }
      })
 }

    //    static requestshare()
    //    {
    //     if(window['wx'])
    //     {
    //         window['wx'].aldSendEvent('分享统计',{'openid' : GameData.Instance.openid})
    //     }
    //     vv.sendPostHttpRequest('https://sjh5.88youxi.cn/app/index.php?i=47&c=entry&do=getonthdp&m=wxs_api',{'zdid':193},(response)=>
    //     {
    //         console.log('请求返回的数据',response)
    
    //         GameData.Instance.thumb = response.data[0].thumb
    //         GameData.Instance.titie = response.data[0].title
            
    
    //     })
    //    }
   
    //  //微信分享
    //  static shareBtnClick()
    //  {
    //     if( window['wx'])
    //     {
    //         window['wx'].aldShareAppMessage({
    //             title: '我刚刚获得了一个新别墅！邀请你来玩哦！',
    //               imageUrl: canvas.toTempFilePathSync({
    //                 destWidth: 500,
    //                 destHeight: 400
    //               }),
    //               success:(res)=>
    //               {
    //                      if(res.shareTickets != undefined && res.shareTickets.length > 0)
    //                      {
    //                          console.log('分享成功！');
    //                      }
    //               }
    //           })
    //     }
    //  }

    /** 打开预制体 url:路径地址,resources\Prefab开始 cb:回调函数 canOPenMore:是否可以多开 */
    static openPrefab(url: string, cb?: Function, canOPenMore?: boolean): cc.Node {
        console.log('qqqqq')
        if (!url) return;
        if (cc.find("Canvas/" + url)){
            let node = cc.find("Canvas/" + url)
            node.active = true
            return;
        }
        cc.loader.loadRes("Prefab/" + url, (err, prefab) => {
            if (err) return;
            let node: cc.Node = cc.instantiate(prefab);
            node.parent = cc.find("Canvas");
            if (cb) cb(node);

            let btnClose: cc.Node = cc.find("btnClose", node);
            if (btnClose) this.btnClick(btnClose, () => { node.destroy() });

            let MASK: cc.Node = node.getChildByName('MASK');
            if (MASK) this.btnClick(MASK, () => { node.destroy() });

            return node;
        });
    }

    static sendPostHttpRequest(url, data, callBackfunc) {
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
                let response = xhr.responseText;
                console.log(response);
              // callBackfunc(response)
                try {
                   callBackfunc(JSON.parse(response));
                } catch (e) {
                    cc.log(e);
                }
            }
        };
        xhr.open("POST", url, false);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send(data);
    }

  
}